<template>
  <div class="page">
    <div class="breadcrumb">
      <span class="bc-item" v-for="(name,i) in breadcrumb" :key="i">{{ name }}</span>
    </div>
    <div class="page-title">测速结果上传</div>
    <van-form>
      <van-field
        v-model="form.img4G"
        required
        label="4G测速"
        :rules="[{ required: true, message: '请上传测速结果照片' }]"
      >
        <template #input>
          <van-uploader
            v-if="checked4G"
            v-model="fileList['4G']"
            upload-text="4G数据测速"
            :max-count="1"
            :before-read="beforeRead"
            :after-read="(file) => afterUpload(file, 'data')"
          />
          <div>
            <van-switch v-model="checked4G" size="20px" />
            &nbsp;&nbsp;
            <span v-if="!checked4G">4G无覆盖</span>
            <span v-else>4G覆盖</span>
          </div>
        </template>
      </van-field>
      <van-field
        v-model="form.img5G"
        required
        label="5G测速"
        :rules="[{ required: true, message: '请上传测速结果照片' }]"
      >
        <template #input>
          <van-uploader
            v-if="checked5G"
            v-model="fileList['5G']"
            upload-text="5G数据测速"
            :max-count="1"
            :before-read="beforeRead"
            :after-read="(file) => afterUpload(file, 'data')"
          />
          <div>
            <van-switch v-model="checked5G" size="20px" />
            &nbsp;&nbsp;
            <span v-if="!checked5G">5G无覆盖</span>
            <span v-else>5G覆盖</span>
          </div>
        </template>
      </van-field>
      <van-field
        required
        label="通话时延"
      >
        <template #input>
          <van-radio-group v-model="callDelay" direction="horizontal">
            <van-radio name="1">良</van-radio>
            <van-radio name="2">差</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        required
        label="通话质量"
      >
        <template #input>
          <van-radio-group v-model="callQuality" direction="horizontal">
            <van-radio name="1">良</van-radio>
            <van-radio name="2">差</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        v-model="form.remark"
        type="textarea"
        rows="2"
        autosize
        label="备注信息"
        placeholder="备注信息"
      />

      <div>
        <van-field
          v-model="form.remark"
          type="textarea"
          rows="2"
          autosize
          label="入户测试">

          <template #input>
            <div>
              <van-switch v-model="ifRoom" size="20px" />
              &nbsp;&nbsp;
              <span v-if="!ifRoom">无入户测试</span>
              <span v-else>入户测试</span>
            </div>
          </template>
        </van-field>
        <div v-if="ifRoom">
          <van-field
            v-model="form.imgRoom"
            required
            label="入户测试"
            :rules="[{ required: true, message: '请上传入户测试图片' }]"
          >
            <template #input>
              <van-uploader
                v-model="fileList['room']"
                upload-text="入户测试图片"
                :max-count="1"
                :before-read="beforeRead"
                :after-read="(file) => afterUpload(file, 'room')"
              />
            </template>
          </van-field>
          <van-field
            required
            v-model="form.userNumber"
            type="textarea"
            rows="2"
            autosize
            label="联系方式"
            placeholder="联系方式"
          />
          <van-field
            required
            v-model="form.houseNumber"
            type="textarea"
            rows="2"
            autosize
            label="门牌号"
            placeholder="门牌号"
          />
        </div>
      </div>
    </van-form>

    <div v-if="finishFlag">
      <div style="margin: 16px; text-align: center">
        <div class="form-btn disabled" >当前小区任务已完成</div>
      </div>
    </div>
    <div v-else>
      <div style="margin: 16px; text-align: center">
        <div class="form-btn" @click="handleSubmit">提交测速结果</div>
<!--        <div class="form-btn" @click="getMd5">获取MD5</div>-->
      </div>
      <div style="margin: 16px; text-align: center" v-if="type === 'YWSW' && posi === '6'">
        <div class="form-btn danger" @click="handleNoUnder">该小区无地下车库</div>
      </div>
      <div style="margin: 16px; text-align: center" v-if="type === 'YWLY' && posi === '4'">
        <div class="form-btn danger" @click="handleNoUnder">该楼栋无电梯</div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  discardVillagePosition,
  getCommunityInfo,
  picVerification,
  submitSpeedResult,
  viewSpeedResult
} from '@/api/publicline/kdcs'
import {uploadCos} from "@/api/common"
import {compressImage, setFileRequestToken} from '@/utils/wyy'
import {geometry, getCurrentLocation} from '@/utils/geo'
import {Dialog, Toast} from 'vant'
import {postAction} from "@api/manage";

export default {
  data() {
    return {
      ifRoom: false,
      checked4G: true,
      checked5G: true,
      finishFlag: false,
      breadcrumb: [],
      form: {},
      fileList: {
        '4G': [],
        '5G': [],
        'room': []
      },
      callDelay: '1',
      callQuality: '1',
      speedresult: 133.45,
      communityInfo: {}
    }
  },
  created() {
    const { communityId, buildingId, type, posi, breadcrumb, speedId } = this.$route.query;
    this.communityId = communityId;
    this.buildingId = buildingId;
    this.type = type;
    this.posi = posi;
    this.speedId = speedId;
    this.breadcrumb = breadcrumb.split('/');

    this.getCommunityInfo()
    if ( this.speedId ) {
      this.loadResult();
    }
    getCurrentLocation( (info) => {
      this.currentLocation = info;
    }, () => {
      Toast.fail("当前定位获取失败")
    } )
  },
  methods: {
    getCommunityInfo() {
      getCommunityInfo( { VILLAGE_ID: this.communityId } )
        .then( res => {
          if ( res.success ) {
            const data = res.result.data;
            this.communityInfo = data;
            this.communityInfo.xqwl = JSON.parse(data.xqwl);
            if(data.state === '2') {
              this.finishFlag = true
            }
          }
        } )
    },
    loadResult() {
      viewSpeedResult( { ID: this.speedId } )
      .then( res => {
        if ( res.success ) {
          const data = res.result.data;
          this.ifRoom = data.ifRoom === '1'
          const pictureUrl = data.pictureUrl
          const pictureUrl4g = data.pictureUrl4g
          const pictureUrl4gMd5 = data.pictureUrl4gMd5
          const pictureUrl5g = data.pictureUrl5g
          const pictureUrl5gMd5 = data.pictureUrl5gMd5
          const pictureUrlRoom = data.pictureUrlRoom
          const callDelay = data.callDelay
          const callQuality = data.callQuality
          const mark = data.mark
          this.checked5G = data.checked5g === '1'
          this.checked4G = data.checked4g == null || data.checked4g === '1'

          this.form = {
            ...data,
            remark: mark
          }
          if(pictureUrl4g !== '' && pictureUrl4g !== null) {
            this.form.img4g = pictureUrl4g
            this.form.img4gMd5 = pictureUrl4gMd5
          }
          if(pictureUrl5g !== '' && pictureUrl5g !== null) {
            this.form.img5g = pictureUrl5g
            this.form.img5gMd5 = pictureUrl5gMd5
          }
          if(pictureUrlRoom !== '' && pictureUrlRoom !== null) {
            this.form.imgRoom = pictureUrlRoom
          }
          this.callDelay = callDelay
          this.callQuality = callQuality
          this.initFileList();
        }
      } )
    },

    initFileList() {
      const splitImg = ( img, md5 ) => {
        return img.split(',').map((item, index) => {
          return {
            url: setFileRequestToken(item),
            md5: md5,
            sourceUrl: item
          };
        });
      }

      if(this.form.img4g) {
        this.fileList["4G"] = splitImg( this.form.img4g, this.form.img4gMd5);
      }
      if(this.form.img5g) {
        this.fileList["5G"] = splitImg( this.form.img5g, this.form.img5gMd5);
      }
      if(this.form.imgRoom) {
        this.fileList["room"] = splitImg( this.form.imgRoom );
      }
    },
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        return compressImage(file);
      }
      Toast('请上传 jpg、png 格式图片')
      return false
    },
    async afterUpload(file, type) {
      file.status = 'uploading'
      file.message = '上传中...'

    const formData = new FormData()
      formData.append('file', file.file)
      formData.append('biz', 'wgyyXccs')
      formData.append('permission', 'public')
      const res = await uploadCos(formData)
      if (res.success) {
        const message = res.message.split('|')
        const newPath = message[0]
        const md5 = message[1]
        if(type === 'data') {
          file.url = newPath
          file.md5 = md5
          file.sourceUrl = newPath
          file.status = 'success'
          file.message = '上传成功'
          // }
        } else {
          file.url = newPath
          file.md5 = md5
          file.sourceUrl = newPath
          file.status = 'success'
          file.message = '上传成功'
        }

      } else {
        file.status = 'failed'
        file.message = res.message
      }
    },
    picVerification(picUrl) {
      const result = picVerification({picUrl: picUrl})
      return result
    },
    handleNoUnder() {
      const center = this.currentLocation
      let xqwl = []
      for ( const item of this.communityInfo.xqwl ) {
        xqwl.push( item.join(',') )
      }
      xqwl = xqwl.join(';')
      geometry(xqwl, center, 'distance', (distance) => {
        if ( distance < 100 ) {
          let message = '';
          if(this.posi === '4') {
            message = '确认该楼栋无电梯?'
          } else if(this.posi === '6') {
            message = '确认该小区无地下停车场?'
          }
          Dialog.confirm({
            title: '操作确认',
            message: message,
          })
            .then(() => {
              // on confirm
              discardVillagePosition( {
                VILLAGE_ID: this.communityId,
                BUILD_NO: this.buildingId,
                POSITION: this.posi,
                TYPE: this.type
              } )
                .then( res => {
                  if ( res.success ) {
                    Toast.success("小区已成功标记")
                    this.$router.go( -1)
                  }
                } )
            })
            .catch(() => {
              // on cancel
            })
        } else {
          Toast.fail('未到达小区范围，不允许提交结果');
        }
      })
    },
    getMd5(){
      postAction('/Xccs/getMd5', {})
        .then((res) => {

        })
    },
    handleSubmit() {
      const center = this.currentLocation
      let xqwl = []
      for ( const item of this.communityInfo.xqwl ) {
        xqwl.push( item.join(',') )
      }
      xqwl = xqwl.join(';')
      geometry(xqwl, center, 'distance', (distance) => {
        if ( distance < 100 ) {
          let url4g = ''
          let url5g = ''
          let url4gMd5 = ''
          let url5gMd5 = ''
          if(this.ifRoom) {
            if ( this.fileList["room"].length === 0 ) {
              Toast.fail("请上传入户测试图片")
              return;
            }
            if ( this.form.userNumber === '' || this.form.userNumber === undefined || this.form.userNumber === null ) {
              Toast.fail("请填写用户号码")
              return;
            }
            if ( this.form.houseNumber === '' || this.form.houseNumber === undefined || this.form.houseNumber === null ) {
              Toast.fail("请填写门派号码")
              return;
            }
          }


          // 如果是移网室外的非中心任务，允许不上传图片
          if(this.type === 'YWSW' && this.posi !== '5') {
            if ( this.checked5G && this.fileList["5G"].length === 0 ) {
              url5g = ''
              url5gMd5 = ''
            } else {
              if(this.checked5G) {
                url5g = this.fileList["5G"][0].sourceUrl;
                url5gMd5 = this.fileList["5G"][0].md5;
                if ( !url5g ) {
                  Toast.fail("5G图片上传失败!")
                  return;
                }
              }
            }
            if ( this.checked4G && this.fileList["4G"].length === 0 ) {
              url4g = ''
              url4gMd5 = ''
            } else {
              if(this.checked4G) {
                url4g = this.fileList["4G"][0].sourceUrl;
                url4gMd5 = this.fileList["4G"][0].md5;
                if ( !url4g ) {
                  Toast.fail("4G图片上传失败！")
                  return;
                }
              }
            }
          } else {
            if ( this.checked5G && this.fileList["5G"].length === 0 ) {
              Toast.fail("请上传5G测速结果图片")
              return;
            }
            if ( this.checked4G && this.fileList["4G"].length === 0 ) {
              Toast.fail("请上传4G测速结果图片")
              return;
            }
            url4g = '';
            url4gMd5 = ''
            if(this.checked4G) {
              url4g = this.fileList["4G"][0].sourceUrl;
              url4gMd5 = this.fileList["4G"][0].md5;
              if ( !url4g ) {
                Toast.fail("4G图片上传失败！")
                return;
              }
            }

            url5g = '';
            url5gMd5 = ''
            if(this.checked5G) {
              url5g = this.fileList["5G"][0].sourceUrl;
              url5gMd5 = this.fileList["5G"][0].md5;
              if ( !url5g ) {
                Toast.fail("5G图片上传失败！")
                return;
              }
            }
          }


          if ( this.callDelay === '' || this.callDelay === undefined || this.callDelay === null ) {
            Toast.fail("请选择通话时延")
            return;
          }
          if ( this.callQuality === '' || this.callQuality === undefined|| this.callQuality === null ) {
            Toast.fail("请选择通话质量")
            return;
          }

          const params = {
            "TYPE": this.type,
            "LOCATION": this.currentLocation,
            "VILLAGE_ID": this.communityId,
            "BUILD_NO": this.buildingId,
            "FLOOR": this.posi,
            "POSITION": this.posi,
            "MARK": this.form.remark,
            "PICTURE_URL_4G": url4g,
            "PICTURE_URL_4G_MD5": url4gMd5,
            "PICTURE_URL_5G": url5g,
            "PICTURE_URL_5G_MD5": url5gMd5,
            'CALL_DELAY': this.callDelay,
            'CALL_QUALITY': this.callQuality,
            'CHECKED5G': this.checked5G ? '1' : '0',
            'CHECKED4G': this.checked4G ? '1' : '0',
            'IF_ROOM': this.ifRoom ? '1' : '0',
            'PICTURE_URL_ROOM': (this.fileList["room"].length === 0) ? '' : this.fileList["room"][0].sourceUrl,
            'USER_NUMBER': this.form.userNumber,
            'HOUSE_NUMBER': this.form.houseNumber
          };
          submitSpeedResult( params )
            .then ( res => {
              if ( res.success ) {
                const data = res.result;
                Toast.success("测速结果提交完成")
                // 打卡成功
                this.$router.go( -1)
              }
            } )
        } else {
          Toast.fail('未到达小区范围，不允许提交结果');

        }
      });
    },
  }
}
</script>

<style lang="less" scoped>
.page {
  background: #FFF;

  .disabled {
    background: #EEE;
    color: #777;
    border-color: #ccc;
  }
}
.page-title {
  font-size: 14px;
  padding: 10px 6px;
  text-align: left;
  display: flex;
  align-items: center;

  &:before {
    content: "";
    display: inline-block;
    width: 4px;
    height: 20px;
    background: #008cff;
    margin-right: 8px;
  }
}
.breadcrumb {
  min-height: 20px;
  border-bottom: 1px solid #ccc;
  font-size: 13px;
  padding: 6px 10px;
  background: #f2f9ff;

  .bc-item {
    color: #888;

    &:after {
      content: " / ";
    }

    &:last-child {
      color: #000;

      &:after {
        content: "";
      }
    }
  }
}
.form-btn {
  padding: 10px 10px;
  border-radius: 4px;
  background: #008cff;
  color: #FFF;

  &.danger {
    background: #ff3700;
    color: #FFF;
  }
}

.borderText::v-deep .van-field--value {
  border: 1px solid red;
}
</style>